package com.construction.api.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.construction.api.domain.dto.SysUserDTO;
import com.construction.api.domain.entity.SysUser;
import com.construction.api.domain.model.token.User;
import com.construction.api.domain.vo.TokenVO;
import com.construction.api.enums.ResultEnum;
import com.construction.api.exception.BusinessException;
import com.construction.api.mapper.SysUserMapper;
import com.construction.api.service.LoginService;
import com.construction.api.service.TokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @author dybin
 * @Date: 2021/7/3 16:05
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final TokenService tokenService;
    private final SysUserMapper sysUserMapper;

    @Override
    public TokenVO login(SysUserDTO sysUserDTO) {
        SysUser sysUser = sysUserMapper.queryUser(sysUserDTO);
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new BusinessException(ResultEnum.BUSINESS_UNUSUAL, "账号名或密码错误");
        }
        boolean validatePassword = validatePassword(sysUserDTO.getPassword(), sysUser.getPassword());
        if (!validatePassword) {
            throw BusinessException.of(ResultEnum.BUSINESS_UNUSUAL, "账号名或密码错误");
        }
        return tokenService.allocateToken(sysUser);
    }

    @Override
    public TokenVO refresh(String oldToken) {
        return tokenService.refreshToken(oldToken);
    }

    @Override
    public Boolean validatePassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        return bcryptPasswordEncoder.matches(rawPassword, encodedPassword);
    }
}
